/**
 * Xinfei.com Inc.
 * Copyright (c) 2004-2023 All Rights Reserved.
 */
package com.xinfei.techplayprod.biz.mq;

import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;

/**
 * 事务消息回调接口，注意一个应用只能有一个回调类
 *
 * @author Chengsheng.Li
 * @version $ MqTranscationListener, v 0.1 2023/10/7 10:31 Chengsheng.Li Exp $
 */

@Component
public class MqTranscationListener implements TransactionListener {

    /*demo测试key*/
    public static String KEY = "key";

    /*
     * 执行本地事务方法
     * @parm msg 消息
     * @parm arg 事务消息附加参数
     * @return LocalTransactionState 本地事务执行结果
     * */
    @Override
    public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        //System.out.println(arg);
        if ("test4".equalsIgnoreCase(msg.getTopic())) {
            return LocalTransactionState.COMMIT_MESSAGE;
        }
        return LocalTransactionState.ROLLBACK_MESSAGE;
    }

    /*
     * 本地回查本地事务状态接口方法
     * @parm msg 消息
     * @return LocalTransactionState 事务状态
     * */
    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt msg) {
        String key = msg.getKeys();
        if (KEY.equalsIgnoreCase(key)) {
            return LocalTransactionState.COMMIT_MESSAGE;
        }
        return LocalTransactionState.ROLLBACK_MESSAGE;
    }
}